package Util;

import java.util.InputMismatchException;
import java.util.Random;
import java.util.Scanner;

public class Utils {
    private Scanner scanner;

    public Utils() {
        this.scanner = new Scanner(System.in);
    }

    // 生成随机6位验证码
    public String generateVerificationCode() {
        // 定义可用的字符集：大小写字母和数字
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 使用 StringBuilder 高效构建验证码
        StringBuilder verificationCode = new StringBuilder();

        // 随机数生成器
        Random random = new Random();

        // 生成6位验证码
        for (int i = 0; i < 6; i++) {
            // 从字符集中随机选择一个字符
            int index = random.nextInt(characters.length());
            verificationCode.append(characters.charAt(index));
        }

        return verificationCode.toString();
    }

    // 获取有效的菜单选择
    public int getValidMenuChoice(int num) {
        int input = 0;
        boolean validInput = false;

        while (!validInput) {
            try {
                input = scanner.nextInt();
                scanner.nextLine(); // 清除缓冲区中的换行符
                if (input >= 0 && input <= num) {
                    validInput = true;
                } else {
                    System.out.println("无效的选择，请输入0到" + num + "之间的数字。");
                    System.out.print("请重新选择操作(0-" + num + "): ");
                }
            } catch (InputMismatchException e) {
                System.out.println("无效的输入，请输入一个整数。");
                System.out.print("请重新选择操作(0-" + num + "): ");
                scanner.next(); // 清除缓冲区中的非整数输入
            }
        }
        return input;
    }

    public boolean isValidPassword(String pwd) {
        return pwd.length() >= 6 && pwd.matches(".*\\d.*") && pwd.matches(".*[a-zA-Z].*");
    }

    public boolean isValidContactInfo(String contactInfo) {
        return contactInfo.isEmpty() || contactInfo.matches("^[A-Za-z0-9+_.-]+@(.+)$") || contactInfo.matches("^\\d{10}$");
    }
}